<template>
  <div class="app-container">
    <!-- 添加或修改SQL脚本管理对话框 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="版本号" disabled="true" prop="version">
              <el-select :disabled="true"  clearable v-model="form.version" placeholder="请选择版本号">
                <el-option
                  v-for="dict in versions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="所属模块" prop="modularId">
              <treeselect  v-model="form.modularId"
                           @select="selectModular"
                           :beforeClearAll="clearSlect"
                           :disabled="disModular"
                           :show-count="true"
                           :multiple="false"
                           :disable-branch-nodes="true"
                           :options="modularTree"
                           placeholder="请选择所属模块"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属客户" prop="customerId">
              <treeselect  v-model="form.customerId"
                           :show-count="true"
                           @select="selectCustomer"
                           :beforeClearAll="clearSlect"
                           :disabled="disCustomer"
                           :multiple="false"
                           :disable-branch-nodes="true"
                           :options="customerTree"
                           placeholder="请选择所属客户"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属报表" prop="reportId">
              <treeselect  v-model="form.reportId"
                           :show-count="true"
                           @select="selectReport"
                           :beforeClearAll="clearSlect"
                           :disabled="disReport"
                           :multiple="false"
                           :disable-branch-nodes="true"
                           :options="reportTree"
                           placeholder="请选择所属报表"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求BUG编号" prop="demandBugId">
              <el-select filterable clearable  @change="changeDemandBugInfo($event)" v-model="form.demandBugId" style="width: 90%" placeholder="请选择需求BUG编号">
                <el-option
                  v-for="demandBugInfo in demandBugInfoList"
                  :key="demandBugInfo.id"
                  :label="`${demandBugInfo.demandBugNum}【${demandBugInfo.description.slice(0,50)}】`"
                  :value="demandBugInfo.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="SQL脚本" prop="sqlScript">
              <monaco-editor ref="monacoEditor"
                             @changeValue="changeValue($event)"
                             style="border:1px solid #000;"
                             :opts="opts"></monaco-editor>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="remark">
              <el-input maxlength="500" clearable v-model="form.remark" type="textarea" placeholder="请输入内容"/>
              <span slot="label">
                <el-tooltip content="描述信息填写提交得脚本是修复什么问题，影响什么功能等信息" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                描述
              </span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否同时存在" prop="coverPrimaryKey">
              <el-radio-group v-model="form.coverPrimaryKey">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}
                </el-radio>
              </el-radio-group>
              <span slot="label">
                <el-tooltip content="某些个性化的数据，例如客户个性化的配置，公用也存在的时候，需要选择同时存在。公用和个性化得后续更新也需要选择是" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                是否同时存在
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新数据标记" prop="dataMark">
              <el-radio-group v-model="form.dataMark">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}
                </el-radio>
              </el-radio-group>
              <span slot="label">
                <el-tooltip content="数据标记的所属报表，所属模块，所属客户不正确的情况，选择是会更新重新覆盖数据对应的标记，注意：调整字段的时候，对应的表也会更新" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                更新数据标记
              </span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item  label="所在分层"  prop="layered">
              <el-select filterable clearable v-model="form.layered" placeholder="报表世界所在分层">
                <el-option
                  v-for="dict in dict.type.report_table_layered"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
              <span slot="label">
                <el-tooltip content="用于区分表所在的分层信息，提交的脚本如果没有建表语句，系统没有提示不需要选择（DWD为数据明细层，DWS为标准层，ADS为数据集市层，DWM为中间层）" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                所在分层
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据库类型" prop="dataBaseType">
              <el-select filterable clearable v-model="form.dataBaseType" placeholder="请选择数据库类型">
                <el-option
                  v-for="dict in dict.type.report_database_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
              <span slot="label">
                <el-tooltip content="用于区很某些字段在库里插入的是一个SQL语句的情况，例如报表数据集的表。系统没有提示不需要选择" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                数据库类型
              </span>
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item v-if="false" label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_common_status"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

    <!-- SQL检查和执行结果 -->
    <el-dialog  :title="titleMsg"  :visible.sync="openMsg" :close-on-click-modal ="false" width="1300px" height="500px" append-to-body>
        <el-col :span="24" style="height:500px">
         <!--  <textarea   v-model="msg" style="width:100%;height: 492px" contenteditable="true">
           </textarea>-->
          <div style="border: 1px solid #CBCBCB;height: 480px;width: 1270px;overflow-x:auto">
            <span style="white-space: pre-wrap;font-size: 12px" v-html="msg"></span>
          </div>
        </el-col>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="subScriptSql" type="primary" :loading="butloading" @click="submitSubScriptSql">确 定</el-button>
        <el-button @click="openMsg = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改需求bug信息对话框 -->
    <el-dialog v-if="openDemandbug"  :title="titleDemandbug" :close-on-click-modal ="false" :visible.sync="openDemandbug" width="800px" append-to-body>
      <el-form ref="form2" :model="form2" :rules="rules2" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="需求BUG编号" prop="demandBugNum">
              <el-input clearable maxlength="30" v-model="form2.demandBugNum" placeholder="请输入需求/者bug编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求/BUG" prop="demandBugType">
              <el-radio-group v-model="form2.demandBugType">
                <el-radio
                  v-for="demandBugType in demandBugTypes"
                  :key="demandBugType.value"
                  :label="parseInt(demandBugType.value)"
                >{{demandBugType.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="外部/内部" prop="demandBugFsource">
              <el-radio-group v-model="form2.demandBugFsource">
                <el-radio
                  v-for="demandBugFsource in demandBugFsources"
                  :key="demandBugFsource.value"
                  :label="parseInt(demandBugFsource.value)"
                >{{demandBugFsource.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求BUG日期" prop="demandBugDate">
              <el-date-picker clearable
                              v-model="form2.demandBugDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择需求BUG日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="需求内容" prop="description">
              <el-input maxlength="500" clearable v-model="form2.description" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本号" prop="version">
              <el-select :disabled="true" clearable v-model="form2.version" placeholder="请选择版本号">
                <el-option
                  v-for="dict in dict.type.report_version"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form2.status">
                <el-radio
                  v-for="dict in dict.type.sys_common_status"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input maxlength="500" clearable v-model="form2.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="butloading" @click="submitForm2">确 定</el-button>
        <el-button  @click="openDemandbug = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {  addScript, updateScript,init,checkSqlScript } from "@/api/reportworld/script";
import { getTableRowStyle } from "@/utils/yss";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import monacoEditor from '@/components/SqlEditor';
import demandbug from "@/views/reportworld/demandbuginfo/index";
import { addInfo} from "@/api/reportworld/demandbuginfo";

export default {
  name: "Script",
  props :["scriptSqlInfo","hisVersion"], // 规则，报表部署包，采集跳转过来传递的数据
  components: {
    monacoEditor,
    Treeselect,
    demandbug
  },
  dicts: ['report_database_type', 'sys_yes_no', 'report_version','sys_common_status','sys_common_status_all','report_table_layered'],
  data() {
    const equalToSqlScript = (rule, value, callback) => {
      if (this.$refs.monacoEditor.getVal()) {
        callback()
      } else {
        callback(new Error("SQL脚本不能为空"));
      }
    };
    return {
      // 数据范围选项
      demandBugTypes: [
        {
          value: 1,
          label: "需求"
        },
        {
          value: 2,
          label: "BUG"
        }
      ],
      demandBugFsources: [
        {
          value: 1,
          label: "外部"
        },
        {
          value: 2,
          label: "内部"
        }
      ],
      butloading:false,
      // 遮罩层
      loading: true,
      //审核和退回按钮禁用
      openMsg:false,
      titleMsg: "",
      msg:"",
      versions:[],
      //所属模块
      modularTree : [],
      // 所属客户
      customerTree: [],
      //所属报表
      reportTree: [],
      // 需求BUG
      demandBugInfoList:[],
      disModular:false,
      disCustomer:false,
      disReport:false,
      isSql:false,
      // 日期范围
      dateRange: [],
      titleDemandbug:'',
      openDemandbug:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        sqlScript: null,
        customerId: null,
        reportId: null,
        modularId: null,
        demandBugId: null,
        layered: null,
        fsource: null,
        dataBaseType: null,
        coverPrimaryKey: null,
        version: null,
        hisVersion:null,
      } ,
      opts: { //编辑器
        value: '',
        readOnly: false, // 是否可编辑
        language: 'sql', // 语言类型
        theme: 'vs', // 编辑器主题
        lineNumbers: "on", // 行号 取值
        lineNumbersMinChars: 6
      },
      // 表单参数
      form: {},
      form2:{},
      formReduction:{},
      // 表单校验
      rules: {
        sqlScript: [
          {
            required: true,
            validator: equalToSqlScript,
            message: "SQL脚本不能为空",
            trigger: ["blur","change"]
          }
        ],
        version: [
          { required: true, message: "版本号不能为空", trigger: "change"}
        ],
        remark: [
          { required: true, message: "描述信息不能为空", trigger: "change"}
        ],
        dataBaseType: [
          { required: true, message: "数据库类型不能为空", trigger: "change"}
        ]
      },
      // 表单校验
      rules2: {
        demandBugNum: [
          { required: true, message: "需求/者bug编号不能为空", trigger: "blur" }
        ],
        demandBugType: [
          { required: true, message: "需求/者bug不能为空", trigger: "change" }
        ],
        demandBugFsource: [
          { required: true, message: "外部/内部不能为空", trigger: "change" }
        ],
        version: [
          { required: true, message: "版本号不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        demandBugDate: [
          { required: true, message: "需求BUG日期不能为空", trigger: "blur" }
        ] ,
        description: [
          { required: true, message: "需求内容不能为空", trigger: "blur" }
        ]
        ,
      }
    };
  },
  mounted() {
    if(this.scriptSqlInfo != undefined && this.scriptSqlInfo){
       this.queryParams.hisVersion = this.hisVersion;
        setTimeout(() => {
          this.init();
          this.handleAdd();
        }, 100);
     }
  },
  methods: {
    /** 新增按钮操作 */
    handleAdd() {
      this.opts.value= '';
      this.reset();
      this.form.version =this.queryParams.hisVersion;
      this.form.coverPrimaryKey = parseInt(this.dict.type.sys_yes_no[1].value);
      this.form.dataMark= parseInt(this.dict.type.sys_yes_no[1].value);
      this.form.status = parseInt(this.dict.type.sys_common_status[0].value);
      this.disModular =false;
      this.disCustomer =false;
      this.disReport =false;
      this.opts.value=this.scriptSqlInfo;
    },
    // 内容改变自动获取值
    changeValue (val) {
      if(val && val.toUpperCase().includes("CREATE TABLE")){
        this.rules.layered = {
          required: true,
          message: "脚本包含建表语句，所在分层不能为空",
          trigger: ["change"]
        };
      }else{
        this.rules.layered = {
          required: false
        };
      }
    },
    init(){
      init(this.queryParams).then(response => {
        this.modularTree=response.modularTree;
        this.customerTree=response.customerTree;
        this.reportTree=response.reportTree;
        this.demandBugInfoList=response.demandBugInfoList;
        this.versions=response.versions;
        this.reductionVersions=response.reductionVersions;
    });
    },
    // 取消按钮
    cancel() {
      this.openMsg =false;
      this.reset();
      this.queryParams.hisVersion="";
      this.init();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sqlScript: null,
        customerId: null,
        reportId: null,
        modularId: null,
        demandBugId: null,
        ftype: null,
        layered: null,
        fsource: null,
        dataBaseType: null,
        coverPrimaryKey: null,
        dataMark: null,
        version: null,
        remark: null,
        status: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        approvalBy: null,
        approvalTime: null,
        hisVersion:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleViewLogger(row){
      this.msg = row.checkLogger;
      this.openMsg = true;
      this.titleMsg ="SQL脚本检查信息";
      this.subScriptSql=false;
    },
    /**
     * 所属客户，所属模块，所属报表，只能选中一个
     */
    selectModular(value){
      this.disCustomer =true;
      this.disReport =true;
      this.disModular =false;
    },
    selectCustomer(value){
      this.disModular =true;
      this.disReport =true;
      this.disCustomer =false;
      // 选择客户后同时存在默认是
      this.form.coverPrimaryKey = parseInt(this.dict.type.sys_yes_no[0].value);
    },
    selectReport(value){
      this.disModular =true;
      this.disCustomer =true;
      this.disReport =false;
    },
    clearSlect(){
      this.disModular =false;
      this.disCustomer =false;
      this.disReport =false;
      this.form.coverPrimaryKey = parseInt(this.dict.type.sys_yes_no[1].value);
      return true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.sqlScript = this.$refs.monacoEditor.getVal();
          if ((this.form.sqlScript.toUpperCase().includes('CREATE TABLE') ||
              this.form.sqlScript.toUpperCase().includes('ALTER TABLE') ||
              this.form.sqlScript.toUpperCase().includes('DROP TABLE') ||
              this.form.sqlScript.toUpperCase().includes('COMMENT ON COLUMN'))
            && (this.form.sqlScript.toUpperCase().includes('INSERT INTO') ||
              (this.form.sqlScript.toUpperCase().includes('UPDATE') && this.form.sqlScript.toUpperCase().includes('SET')) ||
                this.form.sqlScript.toUpperCase().includes('DELETE FROM'))) {
            this.$modal.msgError("CREATE,ALTER,DROP,COMMENT语句需要和INSERT，UPDATE，DELETE脚本分开提交，请检查脚本信息！");
            return;
          }
          this.butloading=true;
          this.$modal.loading("正在检查SQL语句，请稍候...");
          checkSqlScript(this.form).then(response => {
            if(response.msgInfo){
              this.msg = response.msgInfo;
             }
            this.openMsg = true;
            this.titleMsg ="SQL脚本检查信息";
            if(response.result== false){
             this.subScriptSql=false;
             }else{
               this.subScriptSql=true;
          }
        }).finally(() => {this.$modal.closeLoading();this.butloading=false;});
        }
      });
    },
    submitSubScriptSql() {
      this.$refs["form"].validate(valid => {
        if (valid) {
           this.form.sqlScript = this.$refs.monacoEditor.getVal();
           this.form.checkLogger = this.msg;
           this.butloading=true;
            addScript(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openMsg = false;
              this.$parent.$parent.openScript = false;
              this.$parent.$parent.getList();
        }).finally(() => {
                this.butloading=false
              this.queryParams.hisVersion="";
              this.init();
            });
        }
      });
    },
    changeDemandBugInfo(value){
      this.form2 = {
        id: null,
        demandBugNum: null,
        demandBugType: null,
        demandBugFsource: null,
        version: null,
        status: null,
        demandBugDate: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        hisVersion:null,
      };
      if("-1" == value){
        this.$set(this.form, "demandBugId", null);
        this.openDemandbug =true;
        this.titleDemandbug = "添加需求BUG信息";
        this.form2.version = this.form.version;
        this.form2.status = parseInt(this.dict.type.sys_common_status[0].value);
        this.form2.demandBugType = parseInt(this.demandBugTypes[0].value);
        this.form2.demandBugFsource = parseInt(this.demandBugFsources[0].value);
        var date = new Date();
        this.form2.demandBugDate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + (date.getDate());
      }
    },
    /** 提交按钮 */
    submitForm2() {
      this.$refs["form2"].validate(valid => {
        if (valid) {
          this.butloading=true;
          this.form2.hisVersion =this.queryParams.hisVersion;
          addInfo(this.form2).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.openDemandbug = false;
            this.init(); // 重新加载
            this.$set(this.form, "demandBugId", response.msg);
        }).finally(() => {this.butloading=false});
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.queryParams.ids=JSON.stringify(this.ids);
      this.download('reportworld/script/export', {
        ...this.queryParams
      }, `script_${new Date().getTime()}.xlsx`)
    },
    handleExportSql(){
      this.queryParams.ids=JSON.stringify(this.ids);
      this.download('reportworld/script/exportSql', {
        ...this.queryParams
    }, `script_${new Date().getTime()}.sql`)
    },
    tableRowStyle({ row, rowIndex}){
        return getTableRowStyle(row,rowIndex,this.ids);
    },
    rowClick(row, column, event) { //单击行
      this.$refs.script.toggleRowSelection(row);
    }
  }
};
</script>
